<template>
	<div class="system-user-dialog-container">
		<el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="769px">
			<el-form ref="studentUserDialogFormRef" :model="state.ruleForm" size="default" label-width="90px" :rules="rules">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="学号" prop="username">
							<el-input v-model="state.ruleForm.username" placeholder="请输入学号" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="姓名" prop="nickName">
							<el-input v-model="state.ruleForm.nickName" placeholder="请输入用户姓名" clearable></el-input>
						</el-form-item>
					</el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="入学年级" prop="nth">
              <el-input v-model="state.ruleForm.nth" placeholder="请输入入学年级" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="证件类型" prop="idType">
              <el-select v-model="state.ruleForm.idType" placeholder="请选择" clearable class="w100">
                <el-option label="身份证" value="身份证"></el-option>
                <el-option label="护照" value="护照"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="身份证号" prop="userIdCardNumber">
              <el-input v-model="state.ruleForm.userIdCardNumber" placeholder="请输入身份证号" clearable></el-input>
            </el-form-item>
          </el-col>
<!--					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">-->
<!--						<el-form-item label="关联角色">-->
<!--							<el-select v-model="state.ruleForm.roleSign" placeholder="请选择" clearable class="w100">-->
<!--								<el-option label="超级管理员" value="admin"></el-option>-->
<!--								<el-option label="普通用户" value="common"></el-option>-->
<!--							</el-select>-->
<!--						</el-form-item>-->
<!--					</el-col>-->
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" v-if="state.dialog.type=='add'">
						<el-form-item label="班级" prop="orgId">
              <el-tree-select
                  v-model="state.ruleForm.orgId"
                  :data="state.sysOrgData"
                  :render-after-expand="false"
                  style="width: 500px"
                  filterable
                  show-all-levels
              />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="性别" prop="gender">
							<el-select v-model="state.ruleForm.gender" placeholder="请选择" clearable class="w100">
								<el-option label="男"  :value="0"></el-option>
								<el-option label="女"  :value="1"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
<!--					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">-->
<!--						<el-form-item label="账户密码">-->
<!--							<el-input v-model="state.ruleForm.password" placeholder="请输入" type="password" clearable></el-input>-->
<!--						</el-form-item>-->
<!--					</el-col>-->
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="用户状态">
              <el-select v-model="state.ruleForm.isDelete" placeholder="请选择"  class="w100" :disabled="state.ruleForm.isDelete==0">
                <el-option label="正常"  :value="0"></el-option>
                <el-option label="禁用"  :value="1"></el-option>
              </el-select>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit(studentUserDialogFormRef)" size="default">{{ state.dialog.submitTxt }}</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="systemUserDialog">
import { reactive, ref} from 'vue';
import {systemApi} from "/@/api/system";
import {userApi} from "/@/api/user";
import {ElMessage, FormInstance, FormRules} from 'element-plus'
const {orgSchoolTree} = systemApi();
const {saveOrUpdateStudent} = userApi();
// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);
const validateIdCard = (rule: any, value: string, callback: any) => {
  const idCardRegex = /(^\d{15}$)|(^\d{18}$)|(^\d{17}[\dXx]$)/;
  if (!value) {
    callback(new Error('请输入身份证号码'));
  } else if(!state.ruleForm.idType){
    callback(new Error('请先选择证件类型'));
  } else if(state.ruleForm.idType=="护照"){
    callback();
  } else if (!idCardRegex.test(value)) {
    callback(new Error('身份证号码格式不正确'));
  } else {
    callback();
  }
};
const rules = reactive<FormRules<RowStudentUserType>>({
  username: [
    { required: true, message: '请输入学号', trigger: 'blur' },
    //{ min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
  ],
  nickName: [
    {
      required: true,
      message: '请输入姓名',
      trigger: 'blur',
    },
  ],
  idType: [
    {
      required: true,
      message: '请选择证件类型',
      trigger: 'change',
    },
  ],
  userIdCardNumber: [
    { required: true,validator: validateIdCard, trigger: 'blur' }, // 添加自定义校验规则
    //{ min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
  ],
  orgId: [
    {
      required: true,
      message: '请选择班级',
      trigger: 'change',
    },
  ],
  gender: [
    {
      required: true,
      message: '请选择性别',
      trigger: 'change',
    },
  ],

})

// 定义变量内容
const studentUserDialogFormRef = ref();
const state = reactive({
	ruleForm: {
    id: '',
    username: '',
    orgId: '',
    orgName: '',
    nickName: '',
    userType: 1,
    gender: 0,
    userMobile: '',
    idType: '',
    userIdCardNumber: '',
    nth: '',
    gmtCreate: '',
    isDelete: 0,
    gmtModified: '',
	},
  sysOrgData: [] as OrgTreeType[], // 部门数据
	dialog: {
		isShowDialog: false,
		type: '',
		title: '',
		submitTxt: '',
	},
});

// 打开弹窗
const openDialog = (type: string, row: RowStudentUserType) => {
	if (type === 'edit') {
		state.ruleForm = JSON.parse(JSON.stringify(row));
		state.dialog.title = '修改学生';
		state.dialog.submitTxt = '修 改';
	} else {
		state.dialog.title = '新增学生';
		state.dialog.submitTxt = '新 增';
    clearForm();
	}
  state.dialog.type = type;
	state.dialog.isShowDialog = true;
	getMenuData();
};
// 关闭弹窗
const closeDialog = () => {
	state.dialog.isShowDialog = false;
};
// 取消
const onCancel = () => {
	closeDialog();
};
// 提交
// const onSubmit = () => {
// 	closeDialog();
// 	emit('refresh');
// 	// if (state.dialog.type === 'add') { }
// };
const onSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      state.ruleForm.userType = 1;
      const res = await saveOrUpdateStudent(state.ruleForm)
      if (res.status === 200) {
        ElMessage.success('更改成功');
        emit('refresh');
      }else{
        ElMessage.error('更改失败');
      }
      closeDialog();

    }
  })
}

// 初始化机构数据
const getMenuData = async () => {
  const res = await orgSchoolTree()
  if (res.status === 200) {
    state.sysOrgData = res.data;
  }
};

const clearForm = () => {
  state.ruleForm = {
    id: '',
    username: '',
    orgId: '',
    orgName: '',
    nickName: '',
    userType: 1,
    gender: 0,
    userMobile: '',
    idType: '',
    userIdCardNumber: '',
    nth: '',
    gmtCreate: '',
    isDelete: 0,
    gmtModified: '',
  }
}
// 暴露变量
defineExpose({
	openDialog,
});
</script>
